package com.hddf.project.util;

import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.ServletActionContext;

import com.hddf.project.pojos.User;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.MethodFilterInterceptor;

/**
 * 
 * @author YY
 * 
 */
public class MyStack extends MethodFilterInterceptor {
	private static final long serialVersionUID = 7454419965857563131L;
	private Log logger = LogFactory.getLog(MyStack.class);

	@Override
	protected String doIntercept(ActionInvocation actioninvocation) throws Exception {
		HttpServletRequest req = ServletActionContext.getRequest();
		HttpSession session = req.getSession();
		String url = req.getServletPath();
		if (url.equals(""))
			url += "/";

		if (!url.equals("/safe_login") && !url.equals("/safe_loginPage")) {
			// 若访问后台资源
			// 过滤到login
			// 取出名为user的Session属性
			User user = (User) session.getAttribute("user");
			// 如果没有登陆，都返回重新登陆
			String sbAy = "";
			if (user != null)
				sbAy = (String) session.getAttribute("AYURL");

			url = url.substring(1);
			if (O.ckInStr(sbAy, url) || O.ckauth(url)) {
				log("执行:" + url, req);
				return actioninvocation.invoke();
			} else {
				log("++++++++++++++++++++++++++++++++++**没有权限  " + url + "**++++++++++++++++++++++++++++++++", req);
				return "noAuth";
			}
		}
		return actioninvocation.invoke();
	}

	/**
	 * 操作成功能
	 * 
	 * @param logs
	 *            日志记录内容,例:
	 */
	public void log(String logs, HttpServletRequest request) {

		User uo = (User) HttpUtil.getSession("user");
		if (uo == null) {
			uo = new User();
			uo.setId(0);
			uo.setUsername("匿名用户");
			HttpUtil.setSession("USERS", uo);
		}
		logger.info("IP:" + O.getIpAddr(request) + " &用户ID为" + uo.getId() + "的" + uo.getUsername() + "于" + O.getSdf("S").format(new Date()) + logs);
	}

}
